var util = require('util');
//var tagModel = require('../modules/mongoSchemes').tagModel;
var model = require('../modules/mongoSchemes').todoModel;

var add = function(data,callback) {	
	var newTodo = new model();
	newTodo.title = data.title;
	newTodo.content = data.content;
	newTodo.category_id = data.categoryId;
    newTodo.is_star = data.isStar;
    newTodo.todo_date = data.todoDate;
    newTodo.tag_ids = data.tagIds;

    newTodo.save(function(err, doc){
        if(err){
            util.log("Fatal "+err);
            callback(err);
        }else{
            callback(null, doc);
        }
    });
};

var find = function(condition, callback) {
    model.find(condition)
        .populate('category_id')
        .populate({
            path: 'tag_ids',
            match: {},
            select:'_id title class_name',
            options: {limit: 10}
        })
        .sort({'order':-1})
        .sort({'last_modified_date':-1})
        .exec(callback);
};

var findAll = function(callback) {
    //model.find({}).populate('category_id').populate('tag_ids').exec(callback);
    find({}, callback);
}

var findById = function(id, callback){
    model.findOne({_id: id}).populate('category_id').populate('tag_ids').exec(callback);
};

var findByTitle = function(title, callback){
    model.findOne({title: title},function(err, doc){
        if (err) {
            util.log('Fatal '+ err);
            callback(err, null);
        }
        callback(null, doc);
    });
};

var findExistByTitle = function(id, title, callback){
    model.find({title: title},function(err, docs){
        if (err) {
            util.log('Fatal '+ err);
            callback(err, null);
        }
        var doc = null;
        //console.log(docs)
        if(docs != null && docs.length > 0){
            for (var i = docs.length - 1; i >= 0; i--) {
                if(docs[i]._id != id){
                    doc = docs[i];
                    break;
                }
            };
        }
        callback(null, doc);
    });
};

var remove = function(id, callback) {
    findById(id, function(err, doc) {
        if (err)
            callback(err);
        else {
            util.log(util.inspect(doc));
            doc.remove();
            callback(null);
        }
    });
};

var edit = function(data, callback) {
    model.update({_id:data._id}, { 
            $set: {
                "title": data.title,
                "content": data.content,
                "category_id": data.categoryId,
                "is_star": data.isStar,
                "tag_ids": data.tagIds,
                "todo_date": data.todoDate,
                "last_modified_date": new Date()
            }
        }, callback); 
    /*
    tagModel.where("_id").in(data.tagIds).exec(function(err, docs){
        model.update({_id:data._id}, { 
            $set: {
                "title": data.title,
                "content": data.content,
                "category_id": data.categoryId,
                "is_star": data.isStar,
                "tag_ids": docs.tagIds,
                "todo_date": new Date(docs.todoDate),
                "last_modified_date": new Date()
            }
        }, callback); 
    });
*/
};

var doneTodo = function(id, isDone, callback) {
    model.update({_id:id}, { 
        $set: { is_done: isDone, 
            order: 20,
            last_modified_date:new Date() }
    }, callback); 
};

var starTodo = function(id, isStar, callback) {
    model.update({_id:id}, { 
        $set: { is_star: isStar }
    }, callback); 
};

var search = function(data, callback){
    var condition = {};
    if(data.keyword && data.keyword.trim() != "")
    {
        condition["$or"] = [
            {"title": new RegExp(data.keyword.trim())}, 
            {"content": new RegExp(data.keyword)}
        ];
    }
    else if(data.title && data.title.trim() != "")
    {
        condition.title = new RegExp(data.title.trim());        
    }
    else if(data.content && data.content.trim() != "")
    {
        condition.content = new RegExp(data.content.trim());        
    }

    if(data.startDate || data.endDate){
        condition.todo_date = {"$gte":data.startDate, "$lte":data.endDate};
    }
    if(data.category && data.category != ""){
        condition.category_id = {"$in":data.category.split(",")};
    }
    if(data.tag && data.tag != ""){
        condition.tag_ids = {"$in":data.tag.split(",")};
    }
    //console.log(condition)
    find(condition, callback);
}

exports.add = add;
exports.find = find;
exports.findAll = findAll;
exports.findById = findById;
exports.findByTitle = findByTitle;
exports.findExistByTitle = findExistByTitle;
exports.remove = remove;
exports.edit = edit;
exports.doneTodo = doneTodo;
exports.starTodo = starTodo;
exports.search = search;
